package selenium;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class test11 {

	public static void main(String[] args) {
		String filepath = "F:\\2017.3.25";// 文件夹路径
		String filepath1 = filepath.replace("\\", "\\\\");
		File fileExist = new File(filepath + "/a.txt");
		if (!fileExist.exists()) {
			File file = new File(filepath);
			if (!file.isDirectory()) {
				System.out.println("这是个文件");
				System.out.println("path=" + file.getPath());
				System.out.println("absolutepath=" + file.getAbsolutePath());
				System.out.println("name=" + file.getName());

			} else if (file.isDirectory()) {
				System.out.println("这是个文件夹");
				System.out.println("path=" + file.getPath());
				System.out.println("absolutepath=" + file.getAbsolutePath());
				System.out.println("name=" + file.getName());
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					method2(filepath + "/a" + ".txt", filepath1 + "/" + filelist[i]);
				}
			}
		}
        
        
	
		final WebDriver driver = new ChromeDriver();
		try {
			driver.manage().window().maximize();
			driver.manage().deleteAllCookies();
			driver.get("http://mp.163.com/index.html");
			SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy hh:mm:ss a",Locale.US);
			
			String name = "NTES_SESS";
			String value1 = "yaQJu0scawjVug26fPhj0z.n.28uBPm4zwm40fuL8_aTFvMZ6bEWi_y2t5h7yFgkVLbGU6oVsHAs8r1TX2AP1wUyqNxcUaW3VjxvM2dddvpPuuCXZ8fVtqf7EskKOdlCOHmhnlaOXrUZcMCupcEHbsDPigPfd0O1d0xLediLzUOoznQcIXvYI8wz_JuxHwYK4";
			String value2 = "T7A4eGt67DURYfsXRC77zvi0NuhoF7o0yVlz4YRbmKxdEox_E6mDyt6qC9iK1tqKVnMFTbCD6KZrHHutKjBnxX1J.x5aJ1DArZRXozCoSluLywd9ltAirEpvM93Nc8mRqGP2ZebXMwLFHritlUpkh.qPuzUUJYqMbU8TP5rMoAws1";
			String value3 = "Bmurv678iHVTdi8repJO7mSrFPf8f5bq_50LZkuS13ewtMe.tG1VzrsgY83IdWihEIZRc7AfiLPC5Bg7sr8bpnI3mPUqHFH4sIgarWaF_n9mtyxk8WL9uKZHHLqWWiZWJ4yHnmCsCJdhNREM5E96FXGpSE5tdOZw2Ley_6.00FrZJ";
			String value4 = "uvWViJknvAxI3n.Cez.Zf9j5alFkhMjpSieIr4jT3V.HZhjsWZ8jzDxpxLwjKc884EeYdAvZugWrASCHu0Z5uld3Vmvo2ZMwG_eVttWKzS6gKsnXMA6c6f1cu0G6NMf6jGRiJFo0mbUFWc.fWAByhN_3HTdf48Rac";
			String value5 ="NLA0yj44xH70S4HpRr1QcLo34PSnJS2DBFwkelft8L1P0pfTK0EfvzdIdAGfC2EElVz21F2r5.Vdr0iBCxGwnpI8L7BWU0aGYmwLxxKCv45_CT9gaj525hb2NDY5qah5fYZFSoWD7HJoK21hKjrspqm8Pt6hlEZ32";
			String value6 = "4ckkv5Z2HyfU27XwVIESQj_8_WDW35QruGN5uFtQUyfIPdtC9PJt3aZ6Zsqt.gJJFE5fJmA2yTjTy28teKAlI5PUye8n_PcqVrNyRR9.3iDB.CAvcTDgDxhg4MVDlcxDtVHG7YnMepmY9gfx9TEKdlrUIQ0xFJH2g";
			String value7 = "OCASBln2y9WIf.1lTnLj6KkeG8Jf4ovvkdNb.MKdcKIba5dR1a4dE8DXDtLdbm44WcJumqeq1vY4a7t_C9mdquzSTGu.7aULA.5fdTUA_aVoJFtd4VuRn0N7Q7q7YLbtYEaiuxTA9qjF5wqyk3hKPTaMnJKodBnp.";
			String value8 = "Gzk9VcyacFmuZaq0btwH.N8NMb_7SKkwUb7ts6LbDLZt5PbfT5eb_gIMI.obt8eeV.dG8CSmebQwx5hmrX2oiqMr94msE5voWsPCb9vW35FqBN.beFmfOp7EjEiElot.l_5um19WyiKNPSiY0XQLd956OBLqb2ORs";
			String value9 = "fwdlclb_3JOiSpWyw3Yba60MogtpNUk6r29z0rd2ud8zeJ2XDeA2YGmSmkb2zOAAxG7Ks4IuW5YRy9IMapiuHzSLICn0yeqbH0JM2IqHle1tVTk2A1nXR_9y5y.yQbzkQYesncIHZ.PTJK.hEwadBIerRVdt2FR30";
			String value10 = "cbRldtkCCPHVB11WucAkI.2mj9Akuxi9UlPwrn_lA_Vw9ylie9Ilb1WsWS3lwxIIgAHWpRzHcUJUgzNxqJwtCu9pJDHrd9f38ryulJf8t9aXh5SlIaHivoPd7dMdz3wSzb96H4J8BME5y0M2L.N_YJ9nvh_XlQvqr";
			String value11 = "Ne6bXrtiG1Z0Ujjoeu0QRL4vDSyXGxBzsu4LFCfeq6a80pfTK0EfvzBC_H3FYjmEchIOHaQWT6ZtOa31e4N24UZKSVV_TjUMD9IhXgapN4BY5guqLiDREOuuukpDDReDT_1xGI12m6fVhrjqFjaiZo15It1gQxOv_";
			String value12 = "ZJI75B3OA3y8NcgD4wfu7mg9UWQN9TU5PRHzIUrx0qWClwr82lQrsyHMJFRmtrMd1eGMiWJc8q4_41dXVTJB67i2bDDj8B.oOgGeLAWwZHT5VAR0zpOSQMRRRYwOOSxO8jmu6Gm9fqrDetB0IBWp4kmVGEmAJuMsj";
			String value13 = "e8MrSzNmjs..grr1RQ8zSX1CzOI34qgV3._sOxq.ZqQsdb.AydB.X5aDbOdzhsyTLjBQx02HYJO3U76dTTW1TSRyEGG2A9306AkyPFIZukAE96qrtwgoJ4fMpVkJ6cv.S8sUclA1f_ahf3rK7XtdTLUDkY24rKWy9";
			String value14 = "0YYMMR78rvm6Y8UaeiBqFIj.evpNV4OQKZPvkJedDVKQOGeEUOReTsg8aI8m9cDvvwYaFKS2EVlg7JUq6DyrboGUHzzfEr1Wy_YwAjKG0PtXLjZDvIy4RaZZZnGyy4dyEf7N5Y7.hVezwxrDkrKIlc7LYu7jSNaTf";
			String value15 = "okqIqQIuqggO4S3xob3ErDjtSQx0lKOytFYCLhZlWa_7cDZbfciZJU6IyhGfyMyq2VU.UeRnJdyueBtqaeglNLa7CqSjec_ysYaHWGgPmkWN9GP.uRU6r8fcdcJB8e0_iI8lQlCDjpXbbsEVPZH3_WJq4K.QJ8UkH";
			String domain = ".mp.163.com";
			String path = "/";
			Date expiry = sdf.parse("5/13/2103 10:31:37 AM");
			Cookie cookie = new Cookie(name, value15, domain, path, expiry);

			driver.manage().addCookie(cookie);
			Thread.sleep(400);
			driver.get("http://mp.163.com/index.html#/income-stat");
			(new WebDriverWait(driver, 50)).until(new ExpectedCondition<WebElement>() {
				@Override
				public WebElement apply(WebDriver arg0) {
					WebElement sDriver = driver.findElement(By.className("slide-entered"));
					if (sDriver != null) {
						return sDriver;
					} else {
						return null;
					}
				}
			});

			WebElement ddElement1 = driver.findElement(By.xpath("//*[@class='column column-5']/div/ul/li[2]/a"));
			String idString = ddElement1.getAttribute("href").toString().replace("http://mp.163.com/article/postpage/",
					"");
			String videoUrl = "http://mp.163.com/video/postpage/" + idString;
			for (int i = 0; i < 6; i++) {

				driver.get(videoUrl + "i=" + i);
				// 读取视频地址
				File filename1 = new File(filepath + "/a.txt"); // 要读取以上路径的input。txt文件
				InputStreamReader reader = new InputStreamReader(new FileInputStream(filename1)); // 建立一个输入流对象reader
				BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
				String line1 = "";
				line1 = br.readLine().trim();
				System.out.println("读入文件成功：" + line1);
				Thread.sleep(200);
				driver.findElement(By.id("video-up-input")).sendKeys(line1);
				Thread.sleep(500);
				// z-red-font读出次数
				WebElement iDriver = driver.findElement(By.className("z-red-font"));
				String iString = iDriver.getText().toString();
				i = Integer.parseInt(iString);

				driver.findElement(By.xpath("//form[@id='videoPost']/div[2]/div[6]/div/ul/li[1]/a/label")).click();
				// 删除第一行
				List<String> list = readFile(filepath + "/a.txt", line1);
				writeFile(filepath + "/a.txt", list);
				// *[@id='videoPost']/div[2]/div[4]/div/div[1]/button
				driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[1]/button")).click();
				Thread.sleep(100);
				driver.findElement(By.linkText("电视剧")).click();

				driver.findElement(By.id("form-tags-input")).sendKeys("电影");
				Actions action = new Actions(driver);
				action.sendKeys(Keys.SPACE).perform();
				driver.findElement(By.id("form-tags-input")).sendKeys("电视剧");
				action.sendKeys(Keys.SPACE).perform();
				driver.findElement(By.id("form-tags-input")).sendKeys("综艺");
				action.sendKeys(Keys.SPACE).perform();
				driver.findElement(By.id("form-tags-input")).sendKeys("明星");
				action.sendKeys(Keys.SPACE).perform();
				driver.findElement(By.id("form-tags-input")).sendKeys("娱乐");
				action.sendKeys(Keys.SPACE).perform();

				File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
				try {
					FileUtils.copyFile(srcFile, new File("d:\\hehe\\" + i + idString + ".png"));
				} catch (IOException e) {
					e.printStackTrace();
				}

				// *[@id='videoPost']/div[2]/div[4]/div/div[2]/button
				// filter-option pull-left
				driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[2]/button")).click();
				Thread.sleep(100);
				driver.findElement(By.linkText("电视剧片段")).click();
				String valueFileTitle = driver.findElement(By.id("fileTitle")).getAttribute("value").trim().replaceAll(" ", "");
				System.out.println("start标题长度为："+valueFileTitle.length());
				System.out.println("start标题为："+valueFileTitle);
				String valueFileTitleNew = valueFileTitle;
				String valueFileTitle1 = valueFileTitle;
				if (valueFileTitle.length() > 27) {
					valueFileTitle1 = valueFileTitle.substring(0, 27);//网易算法有问题所以是28
					System.out.println("end标题长度为："+valueFileTitle1.length());
					System.out.println("end标题为："+valueFileTitle1);
				}
				driver.findElement(By.id("fileTitle")).clear();
				driver.findElement(By.id("fileTitle")).sendKeys(valueFileTitle1);
				driver.findElement(By.id("description")).sendKeys(valueFileTitleNew + "/" + valueFileTitleNew);

				WebDriverWait wait = new WebDriverWait(driver, 50);
				wait.until(new ExpectedCondition<WebElement>() {
					@Override
					public WebElement apply(WebDriver d) {
						WebElement ddElement = driver.findElement(By.className("radio-img"));
						System.out.println("aaaaaaaaaaaaaaaaaaaaa");
						if (ddElement != null) {
							return ddElement;
						} else {
							return null;
						}
					}
				});
				// .//*[@id='auto']/ul/li[5]/input

				driver.findElement(By.xpath("//*[@id='auto']/ul/li[5]")).click();
				// .//*[@id='videoPost']/div[2]/div[7]/button
				driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[7]/button")).click();

				(new WebDriverWait(driver, 50)).until(new ExpectedCondition<WebElement>() {
					@Override
					public WebElement apply(WebDriver arg0) {
						WebElement sDriver = driver.findElement(By.className("js-btn-ok"));
						if (sDriver != null) {
							return sDriver;
						} else {
							return null;
						}
					}
				});
				Thread.sleep(150);
				driver.findElement(By.className("js-btn-ok")).click();
				System.out.println("ssssssssssssssssssssssssssssss");
				if (i == 5) {
					driver.manage().deleteAllCookies();
					System.out.println("endendendendendendendendendend");
					Thread.sleep(200);
					break;
				}
			}
			driver.get("http://dy.163.com/wemedia/login.html");

		} catch (Exception e) {
			e.printStackTrace();
		}
		 driver.quit();
	};




	// 方法1：

	public void method1() {
		FileWriter fw = null;
		try {
			// 如果文件存在，则追加内容；如果文件不存在，则创建文件
			File f = new File("E:\\dd.txt");
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		pw.println("追加内容");
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 方法2：

	public static void method2(String file, String conent) {
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
			out.write(conent + "\r\n");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	// 方法3：

	public static void method3(String fileName, String content) {
		try {
			// 打开一个随机访问文件流，按读写方式
			RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
			// 文件长度，字节数
			long fileLength = randomFile.length();
			// 将写文件指针移到文件尾。
			randomFile.seek(fileLength);
			randomFile.writeBytes(content + "\r\n");
			randomFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static List<String> readFile(String filePath, String str) throws IOException {
		File file = new File(filePath);
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		reader = new BufferedReader(new FileReader(file));
		String text = reader.readLine();
		while (text != null) {
			if (!text.trim().equals(str)) {
				list.add(text + "\r\n");
			}
			text = reader.readLine();
		}
		reader.close();
		return list;
	}

	public static void writeFile(String filePath, List<String> list) throws IOException {
		File file = new File(filePath);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream outputStream = new FileOutputStream(file);
		for (String s : list) {
			outputStream.write(s.getBytes());
		}
		outputStream.close();
	}

}
